package com.pccw.usercentercontroller.config;


import com.pccw.usercentercontroller.vo.BaseRespVO;
import com.pccw.usercenterservice.exception.PccwException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;
import java.nio.file.AccessDeniedException;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalCustomExceptionHandler {


    /**
     * 自定义验证异常
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.info(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return BaseRespVO.fail(message);
    }

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = AccessDeniedException.class)
    public BaseRespVO handler(AccessDeniedException e) {
        log.info("security权限不足：----------------{}", e.getMessage());
        return BaseRespVO.fail("权限不足");
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = ValidationException.class)
    public BaseRespVO handler(ValidationException e) {
        log.info("实体校验异常：----------------{}", e.getMessage());
        return BaseRespVO.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public BaseRespVO handler(IllegalArgumentException e) {
        log.error("Assert异常：----------------{}", e.getMessage());
        return BaseRespVO.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = PccwException.class)
    public BaseRespVO handler(PccwException e) {
        log.error("运行时异常：----------------", e);
        return BaseRespVO.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    public BaseRespVO handler(Exception e) {
        log.error("运行时异常：----------------", e);
        return BaseRespVO.fail("系统异常");
    }
}

